package com.lsht.system.service.impl.siwei;

import com.lsht.common.config.LshtConfig;
import com.lsht.common.core.domain.AjaxResult;
import com.lsht.common.core.domain.model.LoginUser;
import com.lsht.common.utils.FileUploadTool;
import com.lsht.common.utils.StringUtils;
import com.lsht.common.utils.uuid.IdUtils;
import com.lsht.system.domain.siwei.PointShowhidden;
import com.lsht.system.domain.siwei.SiweiPoint;
import com.lsht.system.domain.siwei.SiweiPointDetails;
import com.lsht.system.domain.siwei.business.SiweiVideo;
import com.lsht.system.mapper.siwei.SiweiPointDetailsMapper;
import com.lsht.system.mapper.siwei.SiweiPointMapper;
import com.lsht.system.service.siwei.SiweiPointDetailsService;
import com.lsht.system.util.NullUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDate;
import java.time.Month;
import java.util.*;

/**
 * 点位记录管理Service业务层处理
 *
 * @author zyc
 * @date 2024-08-14
 */
@Service
public class SiweiPointDetailsServiceImpl implements SiweiPointDetailsService {
    @Autowired
    private SiweiPointDetailsMapper siweiPointDetailsMapper;

    @Autowired
    private SiweiPointMapper siweiPointMapper;

    /**
     * 新增点位记录管理
     *
     * @param siweiPointDetails 点位记录管理
     * @param file
     * @param loginUser
     * @return 结果
     */
    @Override
    public int genAdd(SiweiPointDetails siweiPointDetails, List<MultipartFile> files, LoginUser loginUser) {
//        Long userId = loginUser.getUser().getUserId();
//        siweiPointDetails.setUserId(userId);
//        siweiPointDetails.setCreateTime(new Date());
        final String logoUrl = LshtConfig.getProfile() + File.separator + "pointDetails" + File.separator;
        StringBuilder imgPaths = new StringBuilder(); // 用来存储图片路径
        for (MultipartFile file : files) {
            // 设置文件路径
            String originalFilename = file.getOriginalFilename();
            try {
                // 上传并返回新文件名称
                String fileName = FileUploadTool.upload(logoUrl, file, originalFilename);
                // 构建替换后的路径
                String replace = logoUrl.replace(LshtConfig.getProfile(), "/profile") + originalFilename;
                String formattedPath = replace.replaceAll("\\\\", "/");
                // 将路径添加到 imgPaths 中
                if (imgPaths.length() > 0) {
                    imgPaths.append(","); // 如果已经有路径了，先添加逗号
                }
                imgPaths.append(formattedPath); // 添加当前图片路径
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // 最后设置 detailsImg 为逗号分隔的路径
        siweiPointDetails.setDetailsImg(imgPaths.toString());
        //id 不为空走修改
        if (NullUtil.isNotEmpty(siweiPointDetails.getId())) {
            //若用户是admin 则设置userId为null(因为用户id也跟着修改了,变成1的话  用户就无法与地图匹配了)
            return siweiPointDetailsMapper.genUpdateById(siweiPointDetails);
        }
        siweiPointDetails.setId(IdUtils.simpleUUID());
        String s = InspectionRecordGenerator.generateInspectionCode();
        siweiPointDetails.setDetalisNumber(s);
        return siweiPointDetailsMapper.genAdd(siweiPointDetails);
    }

    @Override
    public int addPointDetailsByApp(SiweiPointDetails siweiPointDetails, LoginUser loginUser) {
//        Long userId = loginUser.getUser().getUserId();
//        siweiPointDetails.setUserId(userId);
// siweiPointDetails.setCreateTime(new Date()); // 如果需要，可以设置创建时间
        StringBuilder imgPaths = new StringBuilder(); // 用来存储图片路径

        try {
            List<String> images = siweiPointDetails.getImage();
            if (StringUtils.isNotEmpty(images)) {
                for (String base64Image : images) {
                    if (base64Image != null && base64Image.contains(",")) {
                        String imageData = base64Image.split(",")[1]; // 移除 data URL 前缀
                        byte[] decodedBytes = Base64.getDecoder().decode(imageData);
                        // 生成一个唯一的文件名，结合UUID和当前时间戳
                        String fileName = LshtConfig.getProfile() + File.separator + "pointDetails" + File.separator +
                                System.currentTimeMillis() + "_" + UUID.randomUUID().toString() + ".png";
                        String directoryPath = LshtConfig.getProfile() + File.separator + "pointDetails";
                        File directory = new File(directoryPath);
                        if (!directory.exists()) {
                            directory.mkdirs(); // 创建目录
                        }
                        File file = new File(fileName);
                        try (FileOutputStream fos = new FileOutputStream(file)) {
                            fos.write(decodedBytes); // 将解码后的图片数据写入文件
                        } catch (IOException e) {
                            System.out.println("Error writing image to file: " + e.getMessage() + " for image: " + base64Image);
                            continue; // 如果某个图片保存失败，则跳过当前图片，继续处理后续图片
                        }
                        // 生成相对路径并替换反斜杠为正斜杠
                        String replace = fileName.replace(LshtConfig.getProfile(), "/profile");
                        String formattedPath = replace.replaceAll("\\\\", "/");
                        // 将路径添加到 imgPaths 中
                        if (imgPaths.length() > 0) {
                            imgPaths.append(","); // 如果已经有路径，先加上逗号
                        }
                        imgPaths.append(formattedPath); // 添加当前图片路径
                    } else {
                        System.out.println("Invalid Base64 image data: " + base64Image);
                        continue;
                    }
                }
                // 设置多张图片的路径（逗号分隔的字符串）
                System.out.println("Final image paths: " + imgPaths.toString());
                siweiPointDetails.setDetailsImg(imgPaths.toString());
            } else {
                siweiPointDetails.setDetailsImg(null);
            }
            // 如果 id 不为空，则执行更新操作
            if (NullUtil.isNotEmpty(siweiPointDetails.getId())) {
                siweiPointDetails.setUpdateTime(new Date()); // 更新时间
                return siweiPointDetailsMapper.genUpdateById(siweiPointDetails); // 执行更新
            }
        } catch (Exception e) {
        }
// 如果没有 ID，执行添加操作
        siweiPointDetails.setId(IdUtils.simpleUUID()); // 设置新生成的 ID
        siweiPointDetails.setDetalisNumber(InspectionRecordGenerator.generateInspectionCode());
        return siweiPointDetailsMapper.genAdd(siweiPointDetails); // 执行添加操作
    }

    /**
     * 删除点位记录管理信息
     *
     * @param id 点位记录管理主键
     * @return 结果
     */
    @Override
    public int genDeleteById(List<String> idList) {
        return siweiPointDetailsMapper.genDeleteById(idList);
    }

    /**
     * 修改点位记录管理
     *
     * @param siweiPointDetails 点位记录管理
     * @return 结果
     */
    @Override
    public int genUpdateById(SiweiPointDetails siweiPointDetails) {
        siweiPointDetails.setUpdateTime(new Date());
        return siweiPointDetailsMapper.genUpdateById(siweiPointDetails);
    }

    /**
     * 查询点位记录管理列表
     *
     * @param siweiPointDetails 点位记录管理
     * @return 点位记录管理
     */
    @Override
    public List<SiweiPointDetails> genQueryList(SiweiPointDetails siweiPointDetails) {
        List<String> date = siweiPointDetails.getDate();
        if (NullUtil.isNotNull(date) && date.size() > 0) {
            siweiPointDetails.setBeginTime(date.get(0));
            siweiPointDetails.setEndTime(date.get(1));
        }
        return siweiPointDetailsMapper.genQueryList(siweiPointDetails);
    }

    /**
     * 根据id查询点位记录详情信息
     *
     * @param siweiPointDetails
     * @return
     */
    @Override
    public SiweiPointDetails genQueryById(SiweiPointDetails siweiPointDetails) {
        return siweiPointDetailsMapper.genQueryById(siweiPointDetails);
    }

    /**
     * 大屏查询填报记录为异常的数据
     *
     * @param siweiPointDetails
     * @return
     */
    @Override
    public List<SiweiPointDetails> pointDetailsByAbnormal(SiweiPointDetails siweiPointDetails) {
        List<String> date = siweiPointDetails.getDate();
        if (NullUtil.isNotNull(date) && date.size() > 0) {
            siweiPointDetails.setBeginTime(date.get(0));
            siweiPointDetails.setEndTime(date.get(1));
        }
        return siweiPointDetailsMapper.pointDetailsByAbnormal(siweiPointDetails);
    }

    @Override
    public List<SiweiPointDetails> pointByAbnormal(SiweiPointDetails siweiPointDetails) {
        return siweiPointDetailsMapper.pointByAbnormal(siweiPointDetails);
    }


    @Override
    public List<SiweiPointDetails> inspectionRecord(SiweiPointDetails siweiPointDetails) {
        List<String> date = siweiPointDetails.getDate();
        if (NullUtil.isNotNull(date) && date.size() > 0) {
            siweiPointDetails.setBeginTime(date.get(0));
            siweiPointDetails.setEndTime(date.get(1));
        }
        return siweiPointDetailsMapper.inspectionRecord(siweiPointDetails);
    }

    @Override
    public int editPointStatus(PointShowhidden pointShowhidden) {
        for (String id : pointShowhidden.getIdList()) {
            siweiPointDetailsMapper.editPointStatus(id, pointShowhidden.getShowHidden());
        }
        return 1;
    }

    @Override
    public SiweiVideo addDetailsVideo(MultipartFile file) {
        SiweiVideo siweiVideo = new SiweiVideo();
        siweiVideo.setId(IdUtils.simpleUUID());
        final String logoUrl = LshtConfig.getProfile() + File.separator + "detailsVideo" + File.separator;
        if (NullUtil.isNotEmpty(file)) {
            //设置文件路径
            String originalFilename = file.getOriginalFilename();
            // 上传并返回新文件名称
            try {
                String fileName = FileUploadTool.upload(logoUrl, file, originalFilename);
            } catch (IOException e) {
                e.printStackTrace();
            }
            String replace = logoUrl.replace(LshtConfig.getProfile(), "/profile") + originalFilename;
            siweiVideo.setVideoUrl(replace.replaceAll("\\\\", "/"));
        }
        siweiPointDetailsMapper.addDetailsVideo(siweiVideo);
        return siweiVideo;
    }

    @Override
    public AjaxResult getGrowthRate(SiweiPoint siweiPoint) {
        Integer parameterType = siweiPoint.getParameterType();
        HashMap<Object, Object> resultMap = new HashMap<>();
        if (NullUtil.isNotNull(parameterType)) {
            switch (parameterType) {
                //按年查询
                case 0:
                    //查询去年数据
                    Integer lastYearCount = siweiPointMapper.getLastYearCount(siweiPoint);
                    //查询今年数据
                    Integer thisYearCount = siweiPointMapper.getThisYearCount(siweiPoint);
                    resultMap.put("last", lastYearCount);
                    resultMap.put("this", thisYearCount);
                    return AjaxResult.success(resultMap);
                //按季查询
                case 1:
                    //查询上季度数据
                    Integer lastJdCount = siweiPointMapper.getLastJdCount(siweiPoint);
                    //查询本个季度数据
                    Integer thisJdCount = siweiPointMapper.getThisJdCount(siweiPoint);
                    resultMap.put("last", lastJdCount);
                    resultMap.put("this", thisJdCount);
                    return AjaxResult.success(resultMap);
                //按月查询
                case 2:
                    //查询上月数据
                    Integer lastMonthCount = siweiPointMapper.getLastMonthCount(siweiPoint);
                    //查询本月月数据
                    Integer thisMonthCount = siweiPointMapper.getThisMonthCount(siweiPoint);
                    resultMap.put("last", lastMonthCount);
                    resultMap.put("this", thisMonthCount);
                    return AjaxResult.success(resultMap);
                default:
                    System.out.println("Unknown value");
                    break;
            }
        }
        return AjaxResult.success();
    }

}
